<template>
  <div>
    <!-- 角色列表 -->
    <div v-if="roleList.length" class="role-list">
      <div v-for="(roleItem, index) in roleList" :key="index" :style="showSelectOptions(roleItem)?{marginBottom: 0}:{}" class="role-item">
        <div class="select-user">
          <el-input v-if="showRoleName" v-model="roleItem[roleNameKey]" :maxlength="16" :class="{'isError': getError('role', index).msg}" :placeholder="roleNamePlaceholder" size="small" class="width-160 mr12" @input="removeError" />
          <selectWithoutHttp v-model="roleItem.roleType" :list-data="opeatorTypeList" :class="{'isError': getError('roleType', index).msg}" class="width-160" label-name="name" key-name="id" placeholder="请选择审批角色" @change="roleTypeChange(roleItem)" />
          <!-- 选择自定义人员：2 -->
          <select-custom-user v-if="roleItem.roleType === ROLE_TYPE.CUSTOMIZE" v-model="roleItem.diyUserIdList" :is-error="!!getError('diyUser', index).msg" :diy-user-item-list.sync="roleItem.diyUserList" class="ml12" placeholder="请选择人员" @change="removeError" />
          <!-- 选择部门：1 -->
          <deptSelect
            v-if="roleItem.roleType === ROLE_TYPE.DEPARTMENT"
            v-model="roleItem.departmentList"
            :class="{'isError': getError('dept', index).msg}"
            :element="handelElement()"
            class="width-240 ml12"
            @changeValue="e => changeDept(e, roleItem)" />
          <!-- :class="{'isError': getError('transferdept', index).msg}" -->
          <!-- 主管：5 -->
          <selectWithoutHttp v-if="roleItem.roleType === ROLE_TYPE.DIRECTOR" v-model="roleItem.manageRole" :class="{'isError': getError('manage', index).msg}" :list-data="manageRoleType" class="width-160 ml12" label-name="name" key-name="id" placeholder="主管类型" @change="removeError"/>
          <!-- 指定人员选择字段：7 -->
          <selectWithoutHttp
            v-if="roleItem.roleType === ROLE_TYPE.DESIGNATE"
            v-model="roleItem.designateUserSelect"
            :class="{'isError': getError(ROLE_TYPE.DESIGNATE, index).msg}"
            :list-data="allUserFields"
            clearable
            class="width-160 ml12"
            label-name="name"
            key-name="key"
            placeholder="请选择"
            @change="removeError" />
          <!-- 角色组：9 -->
          <selectWithoutHttp
            v-if="roleItem.roleType === ROLE_TYPE.ROLE_GROUP"
            v-model="roleItem.roleGroup"
            :class="{'isError': getError(ROLE_TYPE.ROLE_GROUP, index).msg}"
            :key="ROLE_TYPE.ROLE_GROUP + index"
            :list-data="roleGroupList"
            clearable
            class="width-160 ml12"
            label-name="name"
            key-name="id"
            placeholder="请选择"
            @change="removeError" />
          <!-- 获取BP指定审批人：10 -->
          <template v-if="roleItem.roleType === ROLE_TYPE.BP_APPROVER">
            <selectWithoutHttp
              v-model="roleItem.bpNames"
              :class="{'isError': !roleItem.bpNames || !roleItem.bpNames.length && getError(ROLE_TYPE.BP_APPROVER, index).msg}"
              :list-data="BPList"
              :filterable="false"
              :key="ROLE_TYPE.BP_APPROVER + index"
              style="margin-left: 10px;"
              class="width-140"
              extend-class="width-long-item"
              placeholder="请选择BP类型"
              key-name="name"
              label-name="name"
              collapse-tags
              multiple
              clearable
              @change="removeError"
            />
            <selectWithoutHttp
              v-if="roleItem.bpNames && roleItem.bpNames.length"
              v-model="roleItem.bpDepts"
              :class="{'isError': getError(ROLE_TYPE.BP_APPROVER, index).msg}"
              :list-data="allDeptFields"
              :filterable="false"
              style="margin-left: 10px;"
              class="width-140"
              extend-class="width-long-item"
              placeholder="请选择"
              key-name="key"
              label-name="name"
              collapse-tags
              multiple
              clearable
              @change="removeError"
            />
          </template>
          <!-- 转交欠款-指定人员字段：12 -->
          <selectWithoutHttp
            v-if="roleItem.roleType === ROLE_TYPE.ARREARS_USERS"
            v-model="roleItem.transferRole"
            :class="{'isError': getError(ROLE_TYPE.ARREARS_USERS, index).msg}"
            :list-data="transferRoleType"
            class="width-160 ml12"
            label-name="name"
            key-name="id"
            placeholder="请选择"
            @change="removeError"/>
          <!-- 指定人员主管：14 -->
          <template v-if="roleItem.roleType === ROLE_TYPE.DESIGNATE_DIRECTOR">
            <selectWithoutHttp
              v-model="roleItem.designateDirectorUser"
              :class="{'isError': !roleItem.designateDirectorUser && getError(ROLE_TYPE.DESIGNATE_DIRECTOR, index).msg}"
              :list-data="allUserFields"
              :key="ROLE_TYPE.DESIGNATE_DIRECTOR + index"
              clearable
              class="width-140 ml12"
              label-name="name"
              key-name="key"
              placeholder="请选择"
              @change="removeError" />
            <selectWithoutHttp
              v-if="roleItem.designateDirectorUser"
              v-model="roleItem.designateDirector"
              :class="{'isError': getError(ROLE_TYPE.DESIGNATE_DIRECTOR, index).msg}"
              :list-data="manageRoleType"
              class="width-140 ml12"
              label-name="name"
              key-name="id"
              placeholder="主管类型"
              @change="removeError"/>
          </template>
          <i class="delete-icon el-icon-delete" @click="deleteRole(index)"/>
          <!-- 错误提示 -->
          <div v-if="getError('role', index).msg" :style="{left: getError('role', index).left || 0}" class="error-tool">{{ getError('role', index).msg }}</div>
          <div v-if="getError('roleType', index).msg" :style="{left: getError('roleType', index).left || 0}" class="error-tool">{{ getError('roleType', index).msg }}</div>
          <div v-if="getError('dept', index).msg" :style="{left: getError('dept', index).left || 0}" class="error-tool">{{ getError('dept', index).msg }}</div>
          <div v-if="getError('diyUser', index).msg" :style="{left: getError('diyUser', index).left || 0}" class="error-tool">{{ getError('diyUser', index).msg }}</div>
          <div v-if="getError('manage', index).msg" :style="{left: getError('manage', index).left || 0}" class="error-tool">{{ getError('manage', index).msg }}</div>
          <div v-if="getError(ROLE_TYPE.DESIGNATE, index).msg" :style="{left: getError(ROLE_TYPE.DESIGNATE, index).left || 0}" class="error-tool">{{ getError(ROLE_TYPE.DESIGNATE, index).msg }}</div>
          <div v-if="getError(ROLE_TYPE.ROLE_GROUP, index).msg" :style="{left: getError(ROLE_TYPE.ROLE_GROUP, index).left || 0}" class="error-tool">{{ getError(ROLE_TYPE.ROLE_GROUP, index).msg }}</div>
          <div v-if="getError(ROLE_TYPE.BP_APPROVER, index).msg" :style="{left: getError(ROLE_TYPE.BP_APPROVER, index).left || 0}" class="error-tool">{{ getError(ROLE_TYPE.BP_APPROVER, index).msg }}</div>
          <div v-if="getError(ROLE_TYPE.ARREARS_USERS, index).msg" :style="{left: getError(ROLE_TYPE.ARREARS_USERS, index).left || 0}" class="error-tool">{{ getError(ROLE_TYPE.ARREARS_USERS, index).msg }}</div>
          <div v-if="getError(ROLE_TYPE.DESIGNATE_DIRECTOR, index).msg" :style="{left: getError(ROLE_TYPE.DESIGNATE_DIRECTOR, index).left || 0}" class="error-tool">{{ getError(ROLE_TYPE.DESIGNATE_DIRECTOR, index).msg }}</div>
        </div>
        <div v-if="showSelectOptions(roleItem)" class="select-options">
          <div v-if="showAutoFill(roleItem.roleType)" class="options-item">
            <el-checkbox
              v-model="roleItem.isAutoFill"
              :disabled="[ROLE_TYPE.CREATOR_SUPERIOR, ROLE_TYPE.DIRECTOR, ROLE_TYPE.DESIGNATE, ROLE_TYPE.CREATOR].includes(roleItem.roleType)"
              :true-label="1"
              :false-label="0"
              @change="changeFillParams(roleItem, 'isAutoFill')" >
              <span class="check-span">自动填入</span>
            </el-checkbox>
          </div>
          <div v-if="showRandomFill(roleItem.roleType)" class="options-item">
            <el-checkbox
              v-model="roleItem.isRandomFill"
              :true-label="1"
              :false-label="0"
              @change="changeFillParams(roleItem, 'isRandomFill')" >
              <span class="check-span">随机填入</span>
            </el-checkbox>
          </div>
          <!-- roleType  0:任务创建人 1:选择部门 2:自定义人员 3:不限制审批人 4:申请人 5:主管 -->
          <div v-if="showAllow(roleItem)" class="options-item">
            <el-checkbox v-model="roleItem.allowSelectOther" :true-label="1" :false-label="0" ><span class="check-span">允许选择其他人员</span></el-checkbox>
          </div>
          <div v-if="showRoleName && [ROLE_TYPE.DEPARTMENT, ROLE_TYPE.CUSTOMIZE, ROLE_TYPE.UNLIMITED, ROLE_TYPE.BP_APPROVER].includes(roleItem.roleType)" class="options-item">
            <el-checkbox v-model="roleItem.userRelation" :true-label="1" :false-label="0" ><span class="check-span">人员审批关系为且</span></el-checkbox>
          </div>
        </div>
      </div>
    </div>
    <EmptyPlaceholder v-else-if="showEmpty" :empty-text-top="0" style="margin-bottom: 20px;" />

    <PlainCreateBtn v-if="!hideBtn" @click="addExamineRoles">{{ btnText }}</PlainCreateBtn>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
// components
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectCustomUser from '../model/selectCustomUser';
import deptSelect from '@/views/legal/process/components/formMake/components/deptSelect';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { ROLE_TYPE, FIXED_PROCESS_TYPE } from '@/utils/const/process';

export default {
  components: { selectCustomUser, deptSelect, selectWithoutHttp, EmptyPlaceholder },
  model: {
    prop: 'roleList',
    event: 'changeRole'
  },
  props: {
    roleList: {
      type: Array,
      default: () => ([])
    },
    errorRolesIds: {
      type: Array,
      default: () => ([])
    },
    roleNameKey: {
      type: String,
      default: 'roleName'
    },
    showRoleName: {
      type: Boolean,
      default: true
    },
    hideBtn: {
      type: Boolean,
      default: false
    },
    showEmpty: {
      type: Boolean,
      default: false
    },
    roleNamePlaceholder: {
      type: String,
      default: '角色名称'
    },
    btnText: {
      type: String,
      default: '添加角色'
    },
    maxlength: {
      type: Number,
      default: 50
    },
    type: { // 审批模块类型
      type: Number,
      default: 0
    },
    opeatorType: {
      type: Array,
      default: () => {
        return [
          { id: ROLE_TYPE.CREATOR, name: '任务创建人' },
          { id: ROLE_TYPE.DEPARTMENT, name: '选择部门' },
          { id: ROLE_TYPE.CUSTOMIZE, name: '自定义人员' },
          { id: ROLE_TYPE.UNLIMITED, name: '不限制审批人' },
          { id: ROLE_TYPE.PROPOSER, name: '申请人' },
          { id: ROLE_TYPE.DIRECTOR, name: '主管' },
          { id: ROLE_TYPE.DESIGNATE, name: '指定人员选择字段' },
          { id: ROLE_TYPE.DESIGNATE_DIRECTOR, name: '指定人员主管' },
          { id: ROLE_TYPE.CREATOR_SUPERIOR, name: '创建人直属上级' },
          { id: ROLE_TYPE.ROLE_GROUP, name: '角色组' },
          { id: ROLE_TYPE.BP_APPROVER, name: '获取BP指定审批人' }
        ];
      }
    }
  },
  data() {
    return {
      ROLE_TYPE,
      manageRoleType: [
        { id: 0, name: '当前部门主管' },
        { id: 1, name: '部门上级主管' },
        { id: 2, name: '部门最高主管' }
      ]
    };
  },
  computed: {
    ...mapState({
      'roleGroupList': state => state.formMake.roleGroups,
      'BPList': state => state.formMake.BPList,
      'allUserFields': state => state.formMake.allUserFields,
      'allDeptFields': state => state.formMake.allDeptFields
    }),
    transferRoleType() {
      return [
        { id: 0, name: '转交人' },
        { id: 1, name: '被转交人' }
      ];
    },
    opeatorTypeList() {
      // 精力分配、签约内审、申请原件、自定义审批不能选择申请人
      const { isFixed } = this.$route.query;
      if (!isFixed) { // 自定义审批
        return this.opeatorType.filter(i => i.id !== ROLE_TYPE.PROPOSER);
      } else if ([FIXED_PROCESS_TYPE.SIGN_UP, FIXED_PROCESS_TYPE.APPLY_ORIGINAL].includes(this.type)) { // 签约内审、申请原件
        return this.opeatorType.filter(i => !this.getTypeMap(this.type, i.id));
      } else if (this.type === FIXED_PROCESS_TYPE.EFFORT_ALLOCATION) { // 精力分配
        return this.opeatorType.filter(i => !this.getTypeMap(this.type, i.id));
      } else if (this.type === FIXED_PROCESS_TYPE.ARREARS_TRANSFER) { // 转交欠款
        const list = this.opeatorType.filter(i => !this.getTypeMap(this.type, i.id));
        return [...list, { id: ROLE_TYPE.ARREARS_USERS, name: '指定人员字段' }];
      } else if (this.type === FIXED_PROCESS_TYPE.TERMINATION) {
        return this.opeatorType.filter(i => !this.getTypeMap(this.type, i.id));
      } else if (this.type === FIXED_PROCESS_TYPE.EXTERNALHARVEST) { // 外采额度申请
        const list = this.opeatorType.filter(i => !this.getTypeMap(this.type, i.id));
        return [...list, { id: ROLE_TYPE.AUTHUSER, name: '授权人' }];
      } else { // 其他固定表单
        return this.opeatorType.filter(i => !this.getTypeMap(this.type, i.id));
      }
    }
  },
  watch: {
    roleList: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val && val.length > 0) {
          val.forEach(item => {
            const temp = this.getTypeMap(this.type, item.roleType);
            if (temp || (this.type === FIXED_PROCESS_TYPE.EFFORT_ALLOCATION && item.roleType === ROLE_TYPE.ARREARS_USERS)) {
              item.roleType = '';
            }
          });
        }
      }
    }
  },
  methods: {
    getTypeMap(type, id) {
      let res = false;
      switch (type) {
        // 自定义表单
        case -1:
          res = [ROLE_TYPE.PROPOSER].includes(id);
          break;
        // 自定义表单
        case 20:
          res = [ROLE_TYPE.PROPOSER].includes(id);
          break;
        // 签约内审
        case FIXED_PROCESS_TYPE.SIGN_UP:
          res = [ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
        // 申请原件
        case FIXED_PROCESS_TYPE.APPLY_ORIGINAL:
          res = [ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
        // 精力分配
        case FIXED_PROCESS_TYPE.EFFORT_ALLOCATION:
          res = [ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
        // 转交欠款
        case FIXED_PROCESS_TYPE.ARREARS_TRANSFER:
          res = [ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
        // 达人解约
        case FIXED_PROCESS_TYPE.TERMINATION:
          res = [ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
        // 外采额度申请
        case FIXED_PROCESS_TYPE.EXTERNALHARVEST:
          res = [ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
        // 其他固定表单
        default:
          res = [ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(id);
          break;
      }
      return res;
    },
    handelElement() {
      const el = {
        type: 'department',
        options: {
          selectChild: true,
          multiple: true,
          placeholder: '请选择部门'
        }
      };
      return el;
    },
    showSelectOptions(roleItem) {
      // roleType  0:任务创建人 1:选择部门 2:自定义人员 3:不限制审批人 4:申请人 5:主管
      if (this.showRoleName) {
        // return roleItem.roleType === 1 || roleItem.roleType === 2 || roleItem.roleType === 3 || roleItem.roleType === 5;
        return roleItem.roleType !== ROLE_TYPE.DEFAULT;
      }
      return this.showAllow(roleItem);
    },
    showAllow(roleItem) {
      return roleItem.roleType !== ROLE_TYPE.UNLIMITED && roleItem.roleType !== ROLE_TYPE.DEFAULT;
    },
    showAutoFill(roleType) {
      return this.showRoleName &&
        [ROLE_TYPE.DEPARTMENT, ROLE_TYPE.CUSTOMIZE, ROLE_TYPE.CREATOR_SUPERIOR,
          ROLE_TYPE.ROLE_GROUP, ROLE_TYPE.DIRECTOR, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR,
          ROLE_TYPE.CREATOR, ROLE_TYPE.BP_APPROVER, ROLE_TYPE.ARREARS_USERS].includes(roleType);
    },
    showRandomFill(roleType) {
      const autoFillDisabled = [ROLE_TYPE.CREATOR_SUPERIOR, ROLE_TYPE.DIRECTOR, ROLE_TYPE.DESIGNATE, ROLE_TYPE.CREATOR].includes(roleType);
      return this.showAutoFill(roleType) && !autoFillDisabled;
    },
    changeFillParams(roleItem, key) {
      const anotherKey = key === 'isAutoFill' ? 'isRandomFill' : 'isAutoFill';
      if (roleItem[key] === 1) {
        this.$set(roleItem, anotherKey, 0);
      }
    },
    getError(type, id) {
      if (this.errorRolesIds.length <= 0) return {};
      return this.errorRolesIds.find(i => i.type === type && i.id === id) || {};
    },
    removeError() {
      this.$emit('removeError');
    },
    roleTypeChange(item) {
      if (item.roleType === ROLE_TYPE.DIRECTOR) {
        if (!item.manageRole) {
          this.$set(item, 'manageRole', 0);
        }
        this.$set(item, 'isAutoFill', 1);
        this.$set(item, 'isRandomFill', 0);
        this.$set(item, 'userRelation', 0);
      } else if ([ROLE_TYPE.PROPOSER, ROLE_TYPE.DEFAULT, ROLE_TYPE.ROLE_GROUP, ROLE_TYPE.BP_APPROVER].includes(item.roleType)) {
        this.$set(item, 'isAutoFill', 0);
        this.$set(item, 'isRandomFill', 0);
        this.$set(item, 'userRelation', 0);
        this.$set(item, 'allowSelectOther', 0);
      } else if (item.roleType === ROLE_TYPE.UNLIMITED) {
        this.$set(item, 'isAutoFill', 0);
        this.$set(item, 'isRandomFill', 0);
        this.$set(item, 'allowSelectOther', 0);
      } else if ([ROLE_TYPE.CREATOR_SUPERIOR, ROLE_TYPE.DESIGNATE, ROLE_TYPE.CREATOR, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(item.roleType)) {
        this.$set(item, 'isAutoFill', 1);
        this.$set(item, 'isRandomFill', 0);
        this.$set(item, 'allowSelectOther', 0);
        this.$set(item, 'userRelation', 0);
      }
      this.removeError();
    },
    changeDept(value, item) {
      const arr = [];
      value.map(it => arr.push(it.id));
      item.departmentIdList = arr;
    },
    deleteRole(index) {
      if (this.roleList && this.roleList.length > 0) {
        this.roleList.splice(index, 1);
      } else {
        this.$emit('changeRole', []);
      }
      this.removeError();
    },
    addExamineRoles() {
      if (this.roleList.length >= this.maxlength) {
        ElMessage.error(`最多可添加${this.maxlength}个`);
        return;
      }
      const examineRole = {
        roleType: ROLE_TYPE.CREATOR,
        departmentList: [],
        diyUserList: [],
        isAutoFill: 1,
        isRandomFill: 0,
        allowSelectOther: 0,
        userRelation: 0
      };
      examineRole[this.roleNameKey] = '';
      this.roleList.push(examineRole);
      this.removeError();
    }
  }
};
</script>

<style lang="scss" scoped>
.delete-icon {
  font-size: 15px;
  color: #333;
  cursor: pointer;
  margin-left: 9px;
}
.check-span {
  color: #666;
  font-size: 14px;
}
.width-160 {
  width: 160px;
  &::v-deep {
    .el-input__inner {
      width: 160px;
    }
  }
}
.width-140 {
  width: 140px;
  &::v-deep {
    .el-input__inner {
      width: 140px;
    }
    .el-cascader__tags, .el-select__tags {
      width: 112px;
      max-width: 112px !important;
      .el-tag > span {
        max-width: 36px;
      }
    }
    .el-select__tags-text {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}
.width-240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.width-120 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
  }
}
.mr12 {
  margin-right: 12px;
}
.ml12 {margin-left: 12px;}
.role-item {
  margin-bottom: 24px;
}
.select-user {
  display: flex;
  align-items: center;
  position: relative;
  .error-tool {
    position: absolute;
    height: 20px;
    font-size: 12px;
    bottom: -20px;
    color: #f56c6c;
  }
}

.select-options {
  margin-top: 17px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #EBEEFD;
  padding-bottom: 13px;
  margin-bottom: 16px;
  .options-item {
    width: 160px;
    margin-right: 12px;
  }
}
.isError {
  &::v-deep {
    .el-input__inner {
      border-color: #f56c6c !important;
    }
  }
}
</style>
